#!/bin/bash -e
source reporting.sh


JAR=bacnetTests/build/libs/bacnet-1.0-SNAPSHOT-all.jar
TARGET="Object name = BACnet device"
TMPOUT=`tempfile`
REPORT=/tmp/report.txt

# Pick the one not-lo inet v4 address.
line=$(ip addr show | fgrep "inet " | fgrep -v 127.0.0.1)

ls -l /config/type/ || true

read -r -a parts <<< "$line"

local_ip=${parts[1]%/*}
broadcast_ip=${parts[3]}

version_test_id="bacnet_VERSION"
pics_test_id="bacnet_PICS"
verbose_output="false"

echo Scanning bacnet $broadcast_ip from $local_ip

java -jar $JAR $pics_test_id $broadcast_ip $local_ip $verbose_output | tee $TMPOUT
java -jar $JAR $version_test_id $broadcast_ip $local_ip $verbose_output | tee $TMPOUT

bacnet_runtime=/config/port/bacnet_runtime.sh
if [ -f $bacnet_runtime ]; then
    echo Processing $bacnet_runtime
    source $bacnet_runtime
fi

if [ -z "$BACNET_EXPECTED" ]; then
    # For testing, consider the presense of bacnet a failure.
    ! fgrep "$TARGET" $TMPOUT
else
    echo Bacnet expected!
    fgrep "$TARGET" $TMPOUT
fi

VERSION_LOG=$(cat tmp/BacnetVersionTest_APPENDIX.txt)
VERSION_RESULT_AND_SUMMARY=$(cat tmp/BacnetVersionTestReport.txt)

PICS_LOG=$(cat tmp/BacnetPICSTest_APPENDIX.txt)
PICS_RESULT_AND_SUMMARY=$(cat tmp/BacnetPICSTestReport.txt)

write_out_result $REPORT \
                 "protocol.bacnet.version" \
                 "Verify and record version of Bacnet used by the device" \
                 "$VERSION_LOG" \
                 "$VERSION_RESULT_AND_SUMMARY"

write_out_result $REPORT \
                 "protocol.bacnet.pic" \
                 "Verify BACnet traffic is compliant to the PIC statement" \
                 "$PICS_LOG" \
                 "$PICS_RESULT_AND_SUMMARY"

result_lines=( "$VERSION_RESULT_AND_SUMMARY" "$PICS_RESULT_AND_SUMMARY" )

echo "logs:"
echo "$VERSION_RESULT_AND_SUMMARY"
echo "$PICS_RESULT_AND_SUMMARY"
